from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from books.models import *
import jwt
import redis
import random
from django.conf import settings
import time
from datetime import datetime

# Create your views here.


# 强制登入装饰器
def login(func):
    def token(self,request,*args,**kwargs):
        tokens = request.headers.get('Authorization')
        try:
            user = jwt.decode(tokens,key=settings.SECRET_KEY,algorithms='HS256')
        except Exception as e:
            return Response({
                'code':403,
                'msg':'用户未登入'
            })
        request.uid = user.get('uid')
        print('>>>>>>>>>>>>dasda',request.uid)

        return func(self,request,*args,**kwargs)
    return token



# 获取验证码
from ronglian_sms_sdk import SmsSDK

accId = 'asdsadfafdsfds'
accToken = 'dasdsasfdfsdgsdg'
appId = 'dasdasfdsfsdgsdg'

def send_message(mobile):
    sdk = SmsSDK(accId, accToken, appId)
    tid = '1'
    # mobile = '手机号1,手机号2'
    code = random.randint(100000,999999)
    datas = (code, 5)
    resp = sdk.sendMessage(tid, mobile, datas)
    print(resp)
    # 验证码存入redis
    rds = redis.Redis(password='123321')
    key = 'sms_%s' % mobile
    rds.set(key,code,ex=60 * 5)
    rds.close()
    return resp


# 发送验证码
class SmsView(APIView):
    def get(self,request,mobile):
        send_message(mobile)

        return Response({
            'code':200,
            'msg':'验证码发送成功',
        })

# 登入注册
class LogonView(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        code = request.data.get('code')

        if not all([mobile,code]):
            return Response({
                'code':400,
                'msg':'接受的数据为空'
            })

        # 判断验证码是否正确
        rds = redis.Redis(password='123321')
        key = 'sms_%s' % mobile

        sms = rds.get(key)

        if not sms:
            return Response({
                'code':400,
                'msg':'验证码已过期'
            })

        if sms.decode() != code:
            return Response({
                'code':400,
                'msg':'验证码错误',
            })

        author = AuthorModel.objects.filter(mobile=mobile).first()
        if not author:
            # 进行注册

            # 生成随机名字
            name = '登达' + mobile[-4:]
            AuthorModel.objects.create(name=name,mobile=mobile)

        author = AuthorModel.objects.filter(mobile=mobile).first()

        token = jwt.encode({
            'uid':author.id,
            'exp':time.time() + 99999
        },key=settings.SECRET_KEY,algorithm='HS256')

        return Response({
            'code':200,
            'msg':'登入成功',
            'name':author.name,
            'token':token
        })


# 文章的增删改查
class ArticleView(APIView):
    def get(self,request):
        article = ArticleModel.objects.all()
        article_list = []
        for i in article:
            article_list.append({
                'id':i.id,
                'article_name':i.article_name,
                'img':i.img,
                'author_id':i.author_id_id,
                'author':{
                    'name':i.author_id.name,
                    'img':i.author_id.img,
                },
                'issue_date':datetime.strftime(i.update_date,'%Y-%m-%d %H:%M:%S'),
                'synopsis':i.synopsis,
            })

        return Response({
            'code':200,
            'msg':"获取成功",
            'data':article_list
        })


    @login
    def post(self,request):
        u_id = request.uid
        article_name = request.data.get('article_name')
        img = request.data.get('img')
        synopsis = request.data.get('synopsis')

        if not all([article_name,img,synopsis]):
            return Response({
                'code':400,
                'msg':'获取的数据为空'
            })

        # 进行添加
        ArticleModel.objects.create(
            article_name=article_name,
            img=img,
            author_id_id=int(u_id),
            synopsis=synopsis,
        )

        return Response({
            'code':200,
            'msg':'发布成功'
        })

    @login
    def put(self,request):
        aid = request.data.get('id')
        name = request.data.get('article_name')
        img = request.data.get('img')
        synopsis = request.data.get('synopsis')

        # 判断此文章是否存在
        article = ArticleModel.objects.filter(id=aid).first()
        if not article:
            return Response({
                'code':400,
                'msg':'没有此文章'
            })

        if name and name != article.article_name:
            article.article_name = name
            article.save()

        if img and img != article.img:
            article.img = img
            article.save()

        if synopsis and synopsis != article.synopsis:
            article.synopsis = synopsis
            article.save()

        article.update_date = datetime.now()
        article.save()
        return Response({
            'code':200,
            'msg':'文章修改成功',
        })

    @login
    def delete(self,request):
        aid = request.query_params.get('id')

        if not aid:
            return Response({
                'code':400,
                'msg':'获取数据为空'
            })
        try:
            ArticleModel.objects.get(id=aid).delete()
            return Response({
                'code':200,
                'msg':'删除成功'
            })
        except Exception as e:
            return Response({
                'code':400,
                'msg':'没有次数据',
            })


class ArticleInfoView(APIView):
    def get(self,request,id):
        try:
            article = ArticleModel.objects.get(id=id)
        except Exception as e:
            print('>>>>>>>>>',e)
            return Response({
                'code':400,
                'msg':"没有次数据"
            })

        return Response({
            'code':200,
            'msg':'获取成功',
            'data':{
                'id':article.id,
                'article_name':article.article_name,
                'author': {
                    'name': article.author_id.name,
                    'img': article.author_id.img,
                },
                'img':article.img,
                'synopsis':article.synopsis,
                'issue_date': datetime.strftime(article.update_date, '%Y-%m-%d %H:%M:%S'),
            }
        })


# 获取上传图片的token
class TokenView(APIView):
    def get(self,request):
        from qiniu import Auth
        access_key = 'NBOdUMU8wchpbyGBP2ANWERP81EPBnmv34dncbtC'
        secret_key = '7eujTnhI_s77xxuus13GVOlpv3_biAokUuQBliZx'
        # 构建鉴权对象
        q = Auth(access_key, secret_key)
        # 要上传的空间
        bucket_name = 'day1031p8'
        # 生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name, expires=3600)
        return Response({
            'code':200,
            'msg':'获取成功',
            'token':token
        })

# 获取用户
class UserView(APIView):
    @login
    def get(self,request):
        u_id = request.uid
        try:
            author = AuthorModel.objects.get(id=u_id)
        except Exception as e:
            print('>>>>>>>>',e)
            return Response({
                'code':400,
                'msg':"此用户不存在"
            })
        return Response({
            'code':200,
            'msg':"获取成功",
            'data':{
                'id':author.id,
                'name':author.name,
                'img':author.img,
                'mobile':author.mobile,
            }
        })

    # 修改用户
    @login
    def put(self,request):
        # 获取前端数据
        img = request.data.get('img')

        u_id = request.uid

        try:
            author = AuthorModel.objects.get(id=u_id)
        except Exception as e:
            print('>>>>>>>>>',e)
            return Response({
                'code':400,
                'msg':"没有此用户"
            })

        author.img = img
        author.save()

        return Response({
            'code':200,
            'msg':'修改成功'
        })





